<template>
  <div class="news-management">
    <ManagementTable
      ref="managementTableRef"
      :search-label="'搜索'"
      :search-placeholder="'新闻标题或作者'"
      :table-title="'新闻管理'"
      :table-data="newsList"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      :item-name="'新闻'"
      :show-add-button="true"
      @search="searchNews"
      @reset="resetSearch"
      @add="showAddNewsDialog"
      @edit="showEditNewsDialog"
      @delete="deleteNews"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      table-width="100%"
    />

    <!-- 添加新闻对话框 -->
    <el-dialog v-model="addNewsDialogVisible" title="添加新闻" width="600px">
      <el-form :model="addNewsForm" :rules="addNewsRules" ref="addNewsFormRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="addNewsForm.title" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="addNewsForm.author" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="addNewsForm.content" type="textarea" :rows="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addNewsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addNews">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑新闻对话框 -->
    <el-dialog v-model="editNewsDialogVisible" title="编辑新闻" width="600px">
      <el-form :model="editNewsForm" :rules="editNewsRules" ref="editNewsFormRef" label-width="100px">
        <el-form-item label="新闻ID" prop="newsId">
          <el-input v-model="editNewsForm.newsId" disabled />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="editNewsForm.title" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="editNewsForm.author" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="editNewsForm.content" type="textarea" :rows="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editNewsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateNews">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import ManagementTable from '@/components/admin/ManagementTable.vue'

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 新闻列表
const newsList = ref([])
const loading = ref(false)

// 管理表格引用
const managementTableRef = ref(null)

// 表格列定义
const columns = [
  { prop: 'id', label: '新闻ID', width: 80 },
  { prop: 'newsTitle', label: '标题' },
  { prop: 'publisher', label: '作者' }
]

// 添加新闻对话框可见性
const addNewsDialogVisible = ref(false)

// 编辑新闻对话框可见性
const editNewsDialogVisible = ref(false)

// 添加新闻表单
const addNewsForm = reactive({
  title: '',
  author: '',
  content: ''
})

// 编辑新闻表单
const editNewsForm = reactive({
  newsId: null,
  title: '',
  author: '',
  content: ''
})

// 添加新闻表单引用
const addNewsFormRef = ref(null)

// 编辑新闻表单引用
const editNewsFormRef = ref(null)

// 添加新闻表单验证规则
const addNewsRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ],
}

// 编辑新闻表单验证规则
const editNewsRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ],
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  // 如果是字符串且包含T，则是ISO格式
  if (typeof dateTime === 'string' && dateTime.includes('T')) {
    return dateTime.replace('T', ' ').substring(0, 19)
  }
  // 如果是Date对象
  if (dateTime instanceof Date) {
    const year = dateTime.getFullYear()
    const month = String(dateTime.getMonth() + 1).padStart(2, '0')
    const day = String(dateTime.getDate()).padStart(2, '0')
    const hours = String(dateTime.getHours()).padStart(2, '0')
    const minutes = String(dateTime.getMinutes()).padStart(2, '0')
    const seconds = String(dateTime.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  return dateTime
}

// 搜索新闻
const searchNews = (keyword) => {
  pagination.pageNum = 1
  fetchNewsList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  pagination.pageNum = 1
  fetchNewsList()
}

// 获取新闻列表
const fetchNewsList = () => {
  loading.value = true
  request.get('/api/admin/news/list', {
    params: {
      keyword: managementTableRef.value?.searchForm.keyword || '',
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }
  }).then(response => {
    if (response.code === 200) {
      // 修改数据处理逻辑，适配后端实际返回的数据结构
      const data = response.data
      if (data && Array.isArray(data.list)) {
        newsList.value = data.list
        pagination.total = data.total || 0
      } else {
        // 如果数据结构不符合预期，使用默认值
        newsList.value = []
        pagination.total = 0
        console.warn('News data structure is not as expected:', data)
      }
    } else {
      ElMessage.error('获取新闻列表失败: ' + response.message)
    }
  }).catch(error => {
    ElMessage.error('获取新闻列表失败: ' + error.message)
  }).finally(() => {
    loading.value = false
  })
}

// 显示添加新闻对话框
const showAddNewsDialog = () => {
  // 重置表单
  Object.assign(addNewsForm, {
    title: '',
    author: '',
    content: ''
  })
  addNewsDialogVisible.value = true
}

// 添加新闻
const addNews = () => {
  addNewsFormRef.value.validate((valid) => {
    if (valid) {
      // 移除状态字段后，如果后端需要调整URL，可修改为：
      request.post('/api/admin/news/add', addNewsForm)
        .then(response => {
          if (response.code === 200) {
            ElMessage.success('新闻添加成功')
            addNewsDialogVisible.value = false
            fetchNewsList()
          } else {
            ElMessage.error('添加新闻失败: ' + response.message)
          }
        })
        .catch(error => {
          ElMessage.error('添加新闻失败: ' + error.message)
        })
    }
  })
}

// 显示编辑新闻对话框
const showEditNewsDialog = (news) => {
  // 填充表单数据
  Object.assign(editNewsForm, {
    newsId: news.id,
    title: news.newsTitle,
    author: news.publisher,
    content: news.newsContent
  })
  editNewsDialogVisible.value = true
}

// 更新新闻
const updateNews = () => {
  editNewsFormRef.value.validate((valid) => {
    if (valid) {
      // 移除状态字段后，如果后端需要调整URL，可修改为：
      request.put('/api/admin/news/update', editNewsForm)
        .then(response => {
          if (response.code === 200) {
            ElMessage.success('新闻更新成功')
            editNewsDialogVisible.value = false
            fetchNewsList()
          } else {
            ElMessage.error('更新新闻失败: ' + response.message)
          }
        })
        .catch(error => {
          ElMessage.error('更新新闻失败: ' + error.message)
        })
    }
  })
}

// 删除新闻
const deleteNews = (news) => {
  ElMessageBox.confirm('确定要删除这条新闻吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete(`/api/admin/news/delete/${news.id}`)
      .then(response => {
        if (response.code === 200) {
          ElMessage.success('新闻删除成功')
          fetchNewsList()
        } else {
          ElMessage.error('删除新闻失败: ' + response.message)
        }
      })
      .catch(error => {
        ElMessage.error('删除新闻失败: ' + error.message)
      })
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.pageNum = 1
  fetchNewsList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.pageNum = val
  fetchNewsList()
}

// 组件挂载时获取新闻列表
onMounted(() => {
  fetchNewsList()
})

// 定义暴露给父组件的方法
defineExpose({
  fetchNewsList
})
</script>

<style scoped>
.news-management {
  padding: 20px;
  background-color: #f5f5f5;
  height: 100%;
}

.news-management :deep(.el-card) {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}
</style>